var WebSocket = require('ws');
var getHistory = require('./history');

const messageList = [];

var sendMessage = function(id, data, type) {
	try {
		if (typeof data == 'string') {
			data = JSON.parse(data);
		}
		var msg = {
			matchId: 174 || id,
			body: data,
		}

		//test
		msg.body.push(msg.body[10]);

		encodeMessage(msg, type);
	} catch(e) {
		console.log(id, data, type);
	}
	
}

var encodeMessage = function(data, type) {
	var body = {
		route: 'messageRoom',
		type: type,
		data: data
	}

	send(body);
}

var socket;

var beginSocket = function(callback) {
	//socket = new WebSocket('ws://121.196.237.206:8010/');
	socket = new WebSocket('ws://127.0.0.1:8010/');

	socket.on('open', function() {
		console.log('open');
		socket.send(JSON.stringify({
			route: 'joinSub',
		}))

		if (callback) {
			callback();
		}
		for(var i = 0; i < messageList.length; i++) {
			socket.send(messageList[i]);
		}

	});

	socket.on('message', function(data) {
		try {
			var data = JSON.parse(data);
			if (data.route == 'messageSub') {
				getHistory(data.data.matchId, sendMessage);
			}
		} catch(e) {

		}
	});

	socket.on('error', function(err) {
		console.log(err);
	});

	socket.on('close', function() {
		console.log('close');
		socket = null;
	});
}

beginSocket();

var send = function(data) {
	var body = JSON.stringify({
		route: 'messageBroad',
		msg: data
	})
	console.log(body);
	if (socket && socket.readyState == 1) {
		socket.send(body);
	} else {
		messageList.push(body);
	}
	//synchro(data);
}

module.exports = {
	sendMessage,
}